<?php

define('Customer', 'Customer');

class sbGoc {

    public function connect() {
        $param = array('soap_version' => SOAP_1_2, 'trace' => 1, "exceptions" => 0, 'cache_wsdl' => 1, 'login' => 'travissite', 'password' => 'travissite');
        try {
            ini_set("soap.wsdl_cache_enabled", "0");
            $client = new \SoapClient(sbValues::URL_GOC_USD, $param);
            return array('status' => true, 'cause' => $client);
        } catch (SoapFault $ex) {
            return array('status' => false, 'cause' => $ex);
        }
    }

    public function search($client, $hotel, $date, $days, $rooms) {
        $d = explode('-', $date);
        return $client->Get_Available_Rooms(
                        array(
                            'apr' => array(
                                'DataSupplierCredentials' => array(
                                    'DataSupplierLogin' => "travissite",
                                    'DataSupplierPassword' => "travissite"
                                ),
                                'ArrivalDate' => array(
                                    'Year' => $d[0],
                                    'Month' => $d[1],
                                    'Day' => $d[2]
                                ),
                                'CustomerID' => Language::TRAVIS_USD,
                                'HotelID' => $hotel,
                                'Days' => $days,
                                'CityCode' => '',
                                'RequestRooms' => array(
                                    'Room' => array(
                                        array(
                                            'Adults' => 2,
                                            'Children' => 0,
                                            'Babies' => 0,
                                            'RoomNumber' => 1,
                                            'RoomType' => '',
                                            'MeanPlan' => '',
                                            'InternalRemarks' => ''
                                        ),
                                    ),
                                ),
                                'LanguageID' => Language::Hebrew,
                            ),
                        )
        );
    }

    public function parseSearchResult($result) {
        $xml = simplexml_load_string($result->Get_Available_RoomsResult, 'SimpleXMLElement', LIBXML_NOCDATA);
        $error = $xml->Error->Text->__toString();
        if ($error === "Not found") {
            return false;
        } else {
            $rooms = array();
            foreach ($xml->Rooms->Room as $room) {
                $max = $room->MaxRoomsOfType->__toString();
                if ($max == "") {
                    $max = 1;
                }
                $temp = array(
                    'room_code' => $room->RoomType->__toString(),
                    'bar_price_usd' => $room->RoomPrice->__toString(),
                    'vacancies' => $max,
                    'key' => $room->RoomSession->SessionID->__toString()
                );
                array_push($rooms, $temp);
            }
            return $rooms;
        }
    }

    public function saveBooking($client, $hotel_id, $session, $date_in, $days, $first_name, $last_name) {
        $date_out = date('Y-m-d', strtotime($date_in . '+' . $days . 'days'));
        $parseDateIn = explode('-', $date_in);
        $parseDateOut = explode('-', $date_out);
        return $client->Save_Booking(
                        array(
                            'b' => array(
                                'VoucherNumber' => '',
                                'DataSupplierCredentials' => array(
                                    'DataSupplierLogin' => "travissite",
                                    'DataSupplierPassword' => "travissite"
                                ),
                                'TravelAgencyName' => 'Travis',
                                'TravelAgentName' => 'Travis',
                                'TravelAgentPhone' => '0545337659',
                                'HotelID' => $hotel_id,
                                'ArrivalDate' => array(
                                    'Year' => $parseDateIn[0],
                                    'Month' => $parseDateIn[1],
                                    'Day' => $parseDateIn[2]
                                ),
                                'DepartureDate' => array(
                                    'Year' => $parseDateOut[0],
                                    'Month' => $parseDateOut[1],
                                    'Day' => $parseDateOut[2]
                                ),
                                'RoomsSessions' => array(
                                    'RoomSession' => array(
                                        'SessionID' => $session,
                                        'CutomerPriceRemark' => '',
                                    )
                                ),
                                'Guests' => array(
                                    'Guest' => array(
                                        'FirstName' => 'Test',
                                        'LastName' => 'Testovich',
                                        'BirthDate' => '',
                                        'AssignedRoom' => '',
                                        'Nationality' => 'ISR'
                                    ),
                                ),
                                'Remarks' => '',
                                'PaymentBy' => Customer,
                                'CustomerID' => Language::TRAVIS_USD,
                                'ExtendedResponse' => false
                            )
                        )
        );
    }

    public function cancelBooking($client, $order_id, $rooms, $hotel_id) {
        return $client->Cancel_Booking(
                        array(
                            'c' => array(
                                'DataSupplierCredentials' => array(
                                    'DataSupplierLogin' => "travissite",
                                    'DataSupplierPassword' => "travissite"
                                ),
                                'BookingMasterNumber' => $order_id,
                                'BookingRoomNumber' => $rooms,
                                'HotelID' => $hotel_id,
                            ),
        ));
    }

    public function parseCancelBooking($result) {
        $xml = simplexml_load_string($result->Cancel_BookingResult);
        if ($xml->Result->Error->Text->__toString() == 'Success') {
            return array(
                'status' => 'Success',
                'cancellation' => $xml->Result->Cancellation->Cancelled->__toString(),
                'code' => $xml->Result->Error->Code->__toString()
            );
        } else {
            return array(
                'status' => 'Unsuccess',
                'cancellation' => 'contact hotel to see if a booking was deleted or not',
                'code' => $xml->Result->Error->Code->__toString()
            );
        }
    }

    public function parseSave($result) {
        $xml = simplexml_load_string($result->Save_BookingResult);
        if ($xml->Booking->Error->Text->__toString() == 'Success') {
            return array(
                'reservation_id' => $xml->Booking->Number->__toString(),
                'reservation_stirng' => $xml
            );
        } else {
            return false;
        }
    }

    public function getHotels($client) {
        return $client->Get_Hotels(
                        array(
                            'a' => array(
                                'DataSupplierCredentials' => array(
                                    'DataSupplierLogin' => "travissite",
                                    'DataSupplierPassword' => "travissite"
                                ),
                                'CustomerID' => Language::TRAVIS_USD
                            ),
        ));
    }

    public function parseGetHotels($result) {
        $xml = simplexml_load_string($result->Get_HotelsResult);
        $hotels = array();

        if ($xml->Error->Text->__toString() == 'Success') {
            foreach ($xml->Hotels->Hotel as $h) {
                $temp = array(
                    'ID' => $h->ID->__toString(),
                    'Name' => $h->Name->__toString(),
                    'Description' => $h->Description->__toString(),
                    'CityCode' => $h->CityCode->__toString(),
                );

                array_push($hotels, $temp);
            }
        }

        return $hotels;
    }

    public function GetAvalibleRoomByCity($client, $city, $date, $days, $rooms) {
        $d = explode('-', $date);
        $arrRooms = $this->parseRoomToXml($rooms);

        return $client->Get_Available_Rooms(
                        array(
                            'apr' => array(
                                'DataSupplierCredentials' => array(
                                    'DataSupplierLogin' => "travissite",
                                    'DataSupplierPassword' => "travissite"
                                ),
                                'ArrivalDate' => array(
                                    'Year' => $d[0],
                                    'Month' => $d[1],
                                    'Day' => $d[2]
                                ),
                                'CustomerID' => Language::TRAVIS_USD,
                                'Days' => $days,
                                'CityCode' => $city,
                                'RequestRooms' => array(
                                    'Room' => $arrRooms,
                                ),
                                'LanguageID' => Language::Hebrew,
                            ),
                        )
        );
    }

    public function parseAvalRoom($result, $civic) {
        $xml = simplexml_load_string($result->Get_Available_RoomsResult, 'SimpleXMLElement', LIBXML_NOCDATA);
        $rooms = array();

        if ($xml->Error->Text->__toString() == 'Success') {
            foreach ($xml->Rooms->Room as $r) {
                $hotelID = $r->HotelID->__toString();
                $price = $this->changeCivic($r->RoomPrice->__toString(), $civic);
                $temp = array(
                    'Session' => $r->RoomSession->SessionID->__toString(),
                    'RoomID' => $r->RoomType->__toString(),
                    'MealPlan' => $r->MealPlan->__toString(),
                    'MealPlanName' => $r->MealPlanName->__toString(),
                    'RoomPrice' => $price['price'],
                    'Currency' => $price['currency'],
                    'MaxRoomsOfType' => $r->MaxRoomsOfType->__toString()
                );

                if (array_key_exists($hotelID, $rooms)) {
                    array_push($rooms[$hotelID], $temp);
                } else {
                    $rooms[$hotelID] = array($temp);
                }
            }
        }

        return $rooms;
    }

    public function insertLocalData($result, $city) {
        $keys = array_keys($result);

        $prices = array();

        foreach ($keys as $k) {
            $hotel = $this->hotelInfoByProviderCode($k);
            if (!is_null($hotel)) {
                $prices[$hotel['id']]['Hotel'] = $hotel;
                $prices[$hotel['id']]['Hotel']['Rooms'] = $this->insertRooms($result[$k]);
            }
        }

        $noprices = $this->insertNotAvailableHotels($prices, $city);

        $localprice = array();
        foreach ($noprices['sort_name'] as $h) {
            $localprice['sort_name'][$h['id']]['Hotel'] = $h;
        }
        
        foreach ($noprices['sort_rate'] as $h) {
            $localprice['sort_rate'][$h['id']]['Hotel'] = $h;
        }

        return array('search' => $prices, 'local_name' => $localprice['sort_name'], 'local_rate' => $localprice['sort_rate']);
    }

    private function insertRooms($data) {
        $rooms = array();

        foreach ($data as $r) {
            $room = $this->roomInfoByProviderCode($r['RoomID']);
            if (!is_null($room)) {
                $room['Price'] = array(
                    'session' => $r['Session'],
                    'bar_price_usd' => $r['RoomPrice'],
                    'bar_price_nis' => 0,
                    'meal_plane' => $r['MealPlan'],
                    'meal_name' => $r['MealPlanName'],
                    'max_room' => $r['MaxRoomsOfType']
                );
                array_push($rooms, $room);
            }
        }

        return $rooms;
    }

    private function hotelInfoByProviderCode($id) {
        $hotel = tblHotelTable::getInstance()->findByDql('provider_code=?', $id)->getFirst();
        if ($hotel) {
            return $hotel->toArray();
        } else {
            return null;
        }
    }

    private function roomInfoByProviderCode($id) {
        $room = tblRoomsTable::getInstance()->findByDql('code_name=?', $id)->getFirst();
        if ($room) {
            return $room->toArray();
        } else {
            return null;
        }
    }

    private function insertNotAvailableHotels($hotels, $city) {
        $keys = array_keys($hotels);

        $where = 'provider_id=' . sbValues::PROVIDER_GOC . ' AND city_id=' . $city;

        foreach ($keys as $k) {
            $where .= ' AND id<>' . $k;
        }

        $objHotelsName = Doctrine_Query::create()->select('*')->from('tblHotel')->where($where)->orderBy('name_en ASC')->execute();
        $arrHotelsName = $objHotelsName->toArray();
        
        $objHotelsRate = Doctrine_Query::create()->select('*')->from('tblHotel')->where($where)->orderBy('stars DESC')->execute();
        $arrHotelsRate = $objHotelsRate->toArray();

        return array('sort_name' => $arrHotelsName, 'sort_rate' => $arrHotelsRate);
    }

    private function parseRoomToXml($rooms) {
        $parse = explode(';', $rooms);

        $arrRooms = array();

        for ($i = 0; $i < count($parse) - 1; $i++) {
            $parseRoom = explode(':', $parse[$i]);

            $temp = array(
                'Adults' => $parseRoom[1],
                'Children' => $parseRoom[2],
                'Babies' => $parseRoom[3],
                'RoomNumber' => 1,
                'RoomType' => '',
                'MeanPlan' => '',
                'InternalRemarks' => ''
            );

            array_push($arrRooms, $temp);
        }

        return $arrRooms;
    }

    private function changeCivic($price, $civic) {
        $p = array();

        $p['price'] = $price;
        $p['currency'] = 'USD';

        if ($civic == sbValues::CIVIC) {
            $dollar = Doctrine_Query::create()->select('*, MAX(date)')->from('tblBank')->execute();

            if ($dollar) {
                $current = $dollar[0]->getCurrent();
                $sum = $price * $current;
                $p['price'] = ceil(($sum * $dollar[0]->getNds()) + $sum);
                $p['currency'] = 'NIS';
            }
        }

        return $p;
    }

}
